/**
 * 
 */
package com.bestbuy.util;

import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookProfile;
import org.springframework.social.facebook.api.impl.FacebookTemplate;

import java.io.IOException;
import java.net.MalformedURLException;

import com.bestbuy.pojo.AccountFacebookInfo;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * @author lyhoang
 *
 */
public class APIWrapper 
{
	private static String appID = "237810709726937";
	private static String appSecrect = "05db0b5cc703fcf96fc902b7ad207015";
	private static String redirectUrl = "http://localhost:8080/bestbuy-project/facebook-callback.do";
	private  String accessToken;
	private Gson gson;
	
	/**
	 * @param accessToken the accessToken to set
	 */
	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	/**
	 * @param gson
	 */
	public APIWrapper() 
	{
		this.gson = gson;
	}
	
	public static String getDialogLink()
	{
		String DialogLink = "https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s";
		return String.format(DialogLink, appID, redirectUrl);
	}

	public static String getAccessToken(String code)
	{
		String accessTokenLink = "https://graph.facebook.com/oauth/access_token?" + 
								"client_id=%s" + "&client_secret=%s" + "&redirect_uri=%s" + "&code=%s"; 
		accessTokenLink = String.format(accessTokenLink, appID, appSecrect, redirectUrl, code);
		String result = NetUtils.GetResult(accessTokenLink);
		String token = result.substring(result.indexOf("=") + 1, result.indexOf("&"));
		// tra ve accessToken
		return token;	
	}
	
	public AccountFacebookInfo getAccountFacebookInfo()
	{
		String infoUrl = "https://graph.facebook.com/me?access_token=%s";
		infoUrl = String.format(infoUrl, this.accessToken);
		String result = NetUtils.GetResult(infoUrl);
		Gson gson = new Gson();
		AccountFacebookInfo account = new AccountFacebookInfo();
		account = gson.fromJson(result, AccountFacebookInfo.class);
		return account;
	}

}
